<template>
  <view class="cart-container">
    <!-- 购物车头部 -->
    <view class="cart-header">
      <text class="header-title">购物车</text>
      <view class="header-actions">
        <text class="edit-btn">编辑</text>
      </view>
    </view>

    <!-- 购物车内容 -->
    <view class="cart-content">
      <!-- 购物车为空时显示 -->
      <view class="empty-cart" v-if="!cartItems || cartItems.length === 0">
        <image src="/static/img/empty-cart.png" class="empty-icon"></image>
        <text class="empty-text">购物车还是空的</text>
        <text class="empty-subtitle">快去挑选心仪的商品吧</text>
      </view>

      <!-- 购物车商品列表 -->
      <view v-else>
        <view class="product-list">
          <view class="product-item" v-for="item in cartItems" :key="item.cartid">
            <checkbox :checked="item.flag" @click="selectProduct(item)" class="product-checkbox" ></checkbox>
            
            <!-- 商品图片 -->
            <view class="product-image">
              <image :src="item.img1" mode="aspectFill" ></image>
            </view>
            
            <!-- 商品信息 -->
            <view class="product-info">
              <text class="product-title">{{item.proname}}</text>
              <text class="product-spec">{{item.spec || '标准规格'}}</text>
              <view class="product-footer">
                <text class="product-price">¥{{item.originprice}}</text>
                <view class="product-actions">
                  <view class="quantity-control">
                    <view class="minus-btn" @click="decreaseQuantity(item.proid)" :disabled="item.num <= 1">-</view>
                    <text class="quantity">{{item.num}}</text>
                    <view class="plus-btn" @click="increaseQuantity(item.proid)">+</view>
                  </view>
                  <view class="delete-btn" @click="showDeleteConfirm(item.cartid)">删除</view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部结算栏 -->
    <view class="cart-footer" v-if="cartItems && cartItems.length > 0">
      <view class="footer-left">
        <checkbox :checked="isAllSelected" @change="selectAll" class="all-checkbox"></checkbox>
        <text class="all-text">全选</text>
        <text class="total-price">合计: ¥{{totalPrice}}</text>
      </view>
      <view class="footer-right">
        <text class="total-count">(共{{selectedCount}}件商品)</text>
        <button class="checkout-btn" :disabled="selectedCount === 0">结算</button>
      </view>
    </view>
  </view>
</template>

<script>
import http from '../../utils/request'
  export default {
    data() {
      return {
        cartItems: [], // 购物车数据，直接存储商品数组
        totalPrice:0,
        selectedCount:0,
        selectedAll:false,
        isAllSelected:false,
      }
    },
    
    onLoad() {
     this.getCartitems()
    },
    onShow(){
      this.getCartitems()
    },
    methods: {
      getCartitems(){
        // 使用封装的http模块，这样token过期时会触发响应拦截器的处理逻辑
        http.post('api/cart/list', {
          userid: uni.getStorageSync('userid')
        }).then(res => {
          console.log(res)
          if(res.data.code==200){
            this.cartItems=res.data.data
          }
        }).catch(err => {
          console.log('获取购物车数据失败:', err)
        })
      },
      
      // 显示删除确认对话框
      showDeleteConfirm(cartid) {
        uni.showModal({
          title: '确认删除',
          content: '确定要从购物车中删除该商品吗？',
          success: (res) => {
            if (res.confirm) {
              this.deleteProduct(cartid);
            }
          }
        });
      },

      // 全选/取消全选
      selectAll(e){
        
      },


      selectProduct(item){
        // 使用封装的http模块
        http.post('api/cart/selectone', {
          cartid: item.cartid,
          flag: !item.flag
        }).then(res => {
          if(res.data.code==200){
            this.getCartitems()
            uni.showToast({
              title:res.data.message,
              icon:'success'
            })
          }
        }).catch(err => {
          console.log('选择商品失败:', err)
        })
      },
      
      // 删除商品的方法框架
      deleteProduct(cartid) {
         console.log(cartid)
         // 使用封装的http模块
         http.post('api/cart/remove', {
           cartid: cartid
         }).then(res => {
           if(res.data.code==200){
             uni.showToast({
               title:res.data.message,
               icon:'success'
             })
             this.getCartitems()
           }
         }).catch(err => {
           console.log('删除商品失败:', err)
         })
      }
    },
    computed:{
      totalPrice(){
        let total=0
        this.cartItems.forEach(item=>{
          if(item){
            total+=item.originprice*item.num
          }
        })
        return total
      },
      selectedCount() {
        let count = 0
        this.cartItems.forEach(item => {
          if(item && item.selected){
            count += item.num
          }
        })
        return count
      },
      // 计算购物车总商品数用于徽标显示
      cartTotalItems() {
        return this.cartItems.reduce((count, item) => count + (item ? item.num : 0), 0);
      }
    },
    watch:{
      // 监听购物车总商品数变化，自动更新徽标
      cartTotalItems(newCount) {
        if (newCount > 0) {
          uni.setTabBarBadge({ index: 1, text: newCount.toString() })
        } else {
          uni.removeTabBarBadge({ index: 1 })
        }
      }
    }
  }
</script>

<style scoped>
  /* 购物车容器 */
  .cart-container {
    width: 100%;
    min-height: 100vh;
    background-color: #f5f5f5;
    display: flex;
    flex-direction: column;
  }
  
  /* 购物车头部 */
  .cart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 24rpx 30rpx;
    background-color: #ffffff;
    border-bottom: 1rpx solid #eeeeee;
  }
  
  .header-title {
    font-size: 36rpx;
    font-weight: 600;
    color: #333333;
  }
  
  .edit-btn {
    font-size: 32rpx;
    color: #666666;
  }
  
  /* 购物车内容 */
  .cart-content {
    flex: 1;
    overflow-y: auto;
  }
  
  /* 空购物车 */
  .empty-cart {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 200rpx 0;
  }
  
  .empty-icon {
    width: 240rpx;
    height: 240rpx;
    margin-bottom: 40rpx;
  }
  
  .empty-text {
    font-size: 36rpx;
    color: #333333;
    margin-bottom: 20rpx;
  }
  
  .empty-subtitle {
    font-size: 28rpx;
    color: #999999;
  }
  
  /* 商品列表 */
  .product-list {
    background-color: #ffffff;
    margin-bottom: 20rpx;
  }
  
  .product-item {
    display: flex;
    padding: 30rpx;
    border-bottom: 1rpx solid #f0f0f0;
  }
  
  .product-item:last-child {
    border-bottom: none;
  }
  
  .product-checkbox {
    transform: scale(0.8);
    margin-right: 20rpx;
    align-self: flex-start;
    margin-top: 30rpx;
  }
  
  .product-image {
    width: 200rpx;
    height: 200rpx;
    margin-right: 24rpx;
    background-color: #f5f5f5;
    overflow: hidden;
  }
  
  .product-image image {
    width: 100%;
    height: 100%;
  }
  
  .product-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }
  
  .product-title {
    font-size: 32rpx;
    color: #333333;
    line-height: 1.4;
    margin-bottom: 12rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }
  
  .product-spec {
    font-size: 28rpx;
    color: #999999;
    margin-bottom: 20rpx;
  }
  
  .product-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .product-price {
    font-size: 36rpx;
    color: #ff6666;
    font-weight: 600;
  }
  
  .quantity-control {
    display: flex;
    align-items: center;
  }
  
  .minus-btn,
  .plus-btn {
    width: 60rpx;
    height: 60rpx;
    border-radius: 50%;
    background-color: #f5f5f5;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 40rpx;
    color: #666666;
  }
  
  .minus-btn:disabled {
    opacity: 0.5;
  }
  
  .quantity {
    width: 80rpx;
    text-align: center;
    font-size: 32rpx;
    color: #333333;
    margin: 0 20rpx;
  }
  
  /* 商品操作区域 */
  .product-actions {
    display: flex;
    align-items: center;
    gap: 30rpx;
  }
  
  /* 删除按钮样式 */
  .delete-btn {
    font-size: 28rpx;
    color: #ff6666;
    padding: 10rpx 20rpx;
    background-color: #fff0f0;
    border-radius: 8rpx;
  }
  
  /* 底部结算栏 */
  .cart-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 24rpx 30rpx;
    background-color: #ffffff;
    border-top: 1rpx solid #eeeeee;
  }
  
  .footer-left {
    display: flex;
    align-items: center;
  }
  
  .all-checkbox {
    transform: scale(0.8);
    margin-right: 16rpx;
  }
  
  .all-text {
    font-size: 32rpx;
    color: #333333;
    margin-right: 30rpx;
  }
  
  .total-price {
    font-size: 36rpx;
    color: #ff6666;
    font-weight: 600;
  }
  
  .footer-right {
    display: flex;
    align-items: center;
  }
  
  .total-count {
    font-size: 28rpx;
    color: #666666;
    margin-right: 20rpx;
  }
  
  .checkout-btn {
    width: 200rpx;
    height: 80rpx;
    line-height: 80rpx;
    background-color: #ff6666;
    color: #ffffff;
    font-size: 32rpx;
    border-radius: 40rpx;
  }
  
  .checkout-btn:disabled {
    background-color: #cccccc;
  }
</style>
